<template>
  <div id="product">
    <div class="search-div">
      <el-form label-width="70px" size="small">
        <el-row>
          <el-col :span="12">
            <el-form-item label="品牌">
              <el-select
                class="m-2"
                v-model="queryRequest.brandId"
                placeholder="选择品牌"
                size="small"
                style="width: 100%"
              >
                <el-option
                  v-for="item in brandList.data"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="分类">
              <el-cascader
                :props="categoryProps"
                style="width: 100%"
                v-model="searchCategoryIdList"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="display: flex">
          <div style="margin: 8px">
            <el-button type="primary" size="small" @click="fetchPage">
              搜索
            </el-button>
            <el-button type="success" size="small" @click="showAdd">
              添加
            </el-button>
            <el-button size="small" @click="resetData">重置</el-button>
          </div>
        </el-row>
      </el-form>
    </div>

    <el-table :data="tableData" style="width: 100%">
      <el-table-column
        prop="sliderUrls"
        label="轮播图"
        #default="scope"
        width="200"
      >
        <div style="height: 50px; float: left">
          <img
            v-for="(item, index) in scope.row.sliderUrls"
            :key="index"
            :src="item"
            width="50"
          />
        </div>
      </el-table-column>
      <el-table-column label="商品名称" prop="name" />
      <el-table-column label="品牌" prop="brandName" />
      <el-table-column label="一级分类" prop="categoryName1" />
      <el-table-column label="二级分类" prop="categoryName2" />
      <el-table-column label="三级分类" prop="categoryName3" />
      <el-table-column label="计量单位" prop="unitName" />
      <el-table-column label="状态" prop="status">
        <template #default="scope">
          {{
            scope.row.status == 0
              ? '未上架'
              : scope.row.status == 1
              ? '上架'
              : '下架'
          }}
        </template>
      </el-table-column>
      <el-table-column label="审核状态" prop="auditMessage" />
      <el-table-column align="center" label="操作">
        <template #default="scope">
          <el-button size="small" @click="showEdit(scope.row)">
            编辑
          </el-button>
          <el-button
            size="small"
            type="success"
            @click="showAudit(scope.row.id)"
          >
            审核
          </el-button>
          <div v-if="scope.row.auditStatus === 1">
            <div v-if="scope.row.status === 1">
              <el-button
                type="warning"
                size="small"
                @click="takeoff(scope.row.id)"
              >
                下架
              </el-button>
            </div>
            <div v-else>
              <el-button
                type="warning"
                size="small"
                @click="takeon(scope.row.id)"
              >
                上架
              </el-button>
            </div>
          </div>
          <div v-else>
            <el-button type="info" size="small" disabled>
              上架
            </el-button>
          </div>
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--    分页页码-->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pageInfo.pageNum"
        v-model:page-size="pageInfo.pageSize"
        :page-sizes="[2, 4, 6, 8]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageInfo.total"
        @size-change="fetchPage"
        @current-change="fetchPage"
      />
    </div>

    <el-dialog
      v-model="dialogVisible"
      :title="action"
      width="70%"
      :disabled="isAudit"
    >
      <el-collapse v-model="activeNames">
        <el-collapse-item title="商品基本信息">
          <div style="margin: 8px">
            商品名称：
          </div>
          <el-input
            v-model="product.name"
            placeholder="商品名称"
            :disabled="isAudit"
          />
          <div style="margin: 8px">
            分类：
          </div>
          <el-form-item>
            <el-cascader
              :props="categoryProps"
              v-model="categoryIdList"
              :disabled="isAudit"
            />
          </el-form-item>
          <div style="margin: 8px">
            品牌：
          </div>
          <el-select
            class="m-2"
            v-model="product.brandId"
            placeholder="选择品牌"
            size="small"
            style="width: 100%"
            :disabled="isAudit"
          >
            <el-option
              v-for="item in brandList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>

          <div style="margin: 8px">
            商品单元：
          </div>
          <el-select
            class="m-2"
            v-model="product.unitName"
            placeholder="商品单元"
            size="small"
            style="width: 100%"
            :disabled="isAudit"
          >
            <el-option
              v-for="item in unitList"
              :key="item.id"
              :label="item.name"
              :value="item.name"
            />
          </el-select>

          <div style="margin: 8px">
            轮播图：
          </div>
          <el-upload
            v-model:file-list="sliderImageList"
            action="http://localhost:8080/admin/product/sliderUpload"
            list-type="picture-card"
            :headers="header"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleSliderRemove"
            :on-success="handleSliderSuccess"
            :disabled="isAudit"
            multiple
          >
            <el-icon>
              <Plus :disabled="isAudit" />
            </el-icon>
          </el-upload>
        </el-collapse-item>

        <el-collapse-item title="商品SKU信息">
          <el-form-item label="选择规格">
            <el-select
              v-model="product.specValue"
              style="width: 100%"
              class="m-2"
              placeholder="选择规格"
              size="default"
              @change="specValueChange"
              :disabled="isAudit"
            >
              <el-option
                v-for="item in specList"
                :key="item.specValue"
                :label="item.specName"
                :value="item.specValue"
              />
            </el-select>
          </el-form-item>

          <div
            class="specValue"
            v-for="(item, index) in specValueList"
            :key="index"
          >
            <span class="tag-group__title">{{ item.key }}</span>
            <el-tag
              class="tag-group__title"
              type="success"
              effect="dark"
              v-for="(specValue, index) in item.valueList"
              :key="index"
            >
              {{ specValue }}
            </el-tag>
          </div>

          <el-form-item label="商品SKU">
            <el-table :data="product.productSkuList" border style="width: 100%">
              <el-table-column prop="skuSpec" label="规格" width="180" />
              <el-table-column
                label="图片"
                #default="scope"
                style="width: 50px"
              >
                <el-upload
                  class="avatar-uploader"
                  action="http://localhost:8080/admin/product/sliderUpload"
                  :show-file-list="false"
                  :headers="header"
                  :on-success="
                    (response, uploadFile, fileList) =>
                      handleSkuSuccess(
                        response,
                        uploadFile,
                        fileList,
                        scope.row
                      )
                  "
                  :disabled="isAudit"
                >
                  <img
                    style="width: 80px"
                    v-if="scope.row.thumbImg"
                    :src="scope.row.thumbImg"
                    class="avatar"
                  />
                  <el-icon v-else class="avatar-uploader-icon">
                    <Plus :disabled="isAudit" />
                  </el-icon>
                </el-upload>
              </el-table-column>
              <el-table-column label="售价" #default="scope">
                <el-input v-model="scope.row.salePrice" :disabled="isAudit" />
              </el-table-column>
              <el-table-column label="市场价" #default="scope">
                <el-input v-model="scope.row.marketPrice" :disabled="isAudit" />
              </el-table-column>
              <el-table-column label="成本价" #default="scope">
                <el-input v-model="scope.row.costPrice" :disabled="isAudit" />
              </el-table-column>
              <el-table-column label="库存数" #default="scope">
                <el-input v-model="scope.row.stockNum" :disabled="isAudit" />
              </el-table-column>
              <el-table-column label="重量" #default="scope">
                <el-input v-model="scope.row.weight" :disabled="isAudit" />
              </el-table-column>
              <el-table-column label="体积" #default="scope">
                <el-input v-model="scope.row.volume" :disabled="isAudit" />
              </el-table-column>
            </el-table>
          </el-form-item>

          <el-form-item label="商品SKU详细信息">
            <div>详细图片</div>
            <el-upload
              v-model:file-list="detailImageList"
              action="http://localhost:8080/admin/product/detailUpload"
              list-type="picture-card"
              :headers="header"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleDetailRemove"
              :on-success="handleDetailSuccess"
              multiple
              :disabled="isAudit"
            >
              <el-icon>
                <Plus :disabled="isAudit" />
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-collapse-item>
        <div v-if="isAudit">
          <el-collapse-item title="审核数据" name="submit" :disabled="true">
            <el-form-item>
              <el-button type="primary" @click="auditPass">通过</el-button>
              <el-button type="primary" @click="auditNotPass">驳回</el-button>
              <el-button @click="dialogVisible = false">取消</el-button>
            </el-form-item>
          </el-collapse-item>
        </div>
        <div v-else>
          <el-collapse-item title="保存修改数据" name="submit" :disabled="true">
            <el-form-item>
              <el-button type="primary" @click="saveOrUpdate">提交</el-button>
              <el-button @click="dialogVisible = false">取消</el-button>
            </el-form-item>
          </el-collapse-item>
        </div>
      </el-collapse>
    </el-dialog>
    <el-dialog v-model="imageVisible">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import {
  findBrandList,
  FindCategoryByParentId,
  findPage,
  findUnitList,
  findSpecList,
  SaveProduct,
  getProductById,
  updateProduct,
  deleteProductById,
  takeonProduct,
  takeoffProduct,
  auditProduct,
} from '@/api/product'
import { useApp } from '@/pinia/modules/app'
import { ElMessage, ElMessageBox } from 'element-plus'

const queryRequest = reactive({
  brandId: '',
  category1Id: '',
  category2Id: '',
  category3Id: '',
})
const pageInfo = reactive({
  pageNum: 1,
  pageSize: 4,
  total: 0,
})
const defaultForm = {
  id: '',
  name: '',
  category1Id: '',
  category2Id: '',
  category3Id: '',
  brandId: '',
  unitName: '',
  sliderUrls: '',
  specValue: '',
  productSkuList: [],
  detailUrls: '',
}

const product = reactive({
  id: '',
  name: '',
  category1Id: '',
  category2Id: '',
  category3Id: '',
  brandId: '',
  unitName: '',
  sliderUrls: '',
  specValue: '',
  productSkuList: [],
  detailUrls: '',
})

// 对话框激活的面板
const activeNames = ref([
  'productBaseInfo',
  'skuInfo',
  'productDetails',
  'submit',
])

const brandList = ref([])
const unitList = ref([])
const tableData = ref([])
const specList = ref([])

// 品牌列表
const getBrandList = async () => {
  const res = await findBrandList()
  brandList.value = res.data
}
// 单元列表
const getUnitList = async () => {
  const res = await findUnitList()
  unitList.value = res.data
}

// 规格列表
const getSpecList = async () => {
  const res = await findSpecList()
  specList.value = res.data
}

// 分类列表
const props = {
  lazy: true,
  value: 'id',
  label: 'name',
  leaf: 'leaf',
  checkStrictly: true,
  async lazyLoad(node, resolve) {
    // 加载数据的方法
    if (typeof node.value == 'undefined') node.value = 0
    const { data } = await FindCategoryByParentId(node.value)
    data.forEach(function(item) {
      //hasChildren判断是否有子节点
      item.leaf = !item.hasChildren
    })
    resolve(data) // 返回数据
  },
}
const categoryProps = ref(props)
const searchCategoryIdList = ref([])

const fetchPage = async () => {
  console.log(searchCategoryIdList.value.length)
  // 处理三级分类的id
  if (searchCategoryIdList.value.length == 1) {
    queryRequest.category1Id = searchCategoryIdList.value[0]
  }

  if (searchCategoryIdList.value.length == 2) {
    queryRequest.category1Id = searchCategoryIdList.value[0]
    queryRequest.category2Id = searchCategoryIdList.value[1]
  }

  if (searchCategoryIdList.value.length == 3) {
    queryRequest.category1Id = searchCategoryIdList.value[0]
    queryRequest.category2Id = searchCategoryIdList.value[1]
    queryRequest.category3Id = searchCategoryIdList.value[2]
  }
  const res = await findPage(pageInfo.pageNum, pageInfo.pageSize, queryRequest)
  tableData.value = res.data.records
  tableData.value.forEach(item => {
    //把字符串转成json对象
    item.sliderUrls = item.sliderUrls.split(',')
  })
  pageInfo.total = res.data.total
}
// resetData 重置
const resetData = () => {
  queryRequest.brandId = ''
  queryRequest.category1Id = ''
  queryRequest.category2Id = ''
  queryRequest.category3Id = ''
  searchCategoryIdList.value = []
  pageInfo.pageSize = 4
  pageInfo.pageNum = 1
  fetchPage()
}
const imageVisible = ref(false)
const dialogVisible = ref(false)
const action = ref('添加或修改')
// 轮播图添加
const sliderImageList = ref([])
const detailImageList = ref([])
const sliderUrlList = ref([])
const detailUrlList = ref([])
const isAudit = ref(false)
const header = {
  token: useApp().authorization.token,
}
const dialogImageUrl = ref('')
// 取消
const handleSliderRemove = (uploadFile, uploadFiles) => {
  sliderUrlList.value.splice(sliderUrlList.value.indexOf(uploadFile.url), 1)
}
const handleDetailRemove = (uploadFile, uploadFiles) => {
  detailUrlList.value.splice(detailUrlList.value.indexOf(uploadFile.url), 1)
}
// 放大
const handlePictureCardPreview = uploadFile => {
  dialogImageUrl.value = uploadFile.url
  imageVisible.value = true
}
// minio处理成功
const handleSliderSuccess = (response, uploadFile) => {
  // product.sliderUrls.push(response.data)
  sliderUrlList.value.push(response.data)
  console.log(sliderUrlList.value)
}
const handleDetailSuccess = (response, uploadFile) => {
  // imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  detailUrlList.value.push(response.data)
}
// sku图片处理成功后
const handleSkuSuccess = (response, uploadFile, fileList, row) => {
  row.thumbImg = response.data
}

const specValueList = ref([])
// 选择规格之后，展示规格详细数据
const specValueChange = () => {
  specValueList.value = JSON.parse(product.specValue)

  // 为后面显示sku表格准备
  const specValueArr = []
  specValueList.value.forEach((item, index) => {
    specValueArr.push(item.valueList)
  })
  // last为上次运算的结果，current为数组中的当前元素
  var result = specValueArr.reduce((last, current) => {
    const array = []
    last.forEach(par1 => {
      current.forEach(par2 => {
        array.push(par1 + ' + ' + par2)
      })
    })
    return array
  })

  console.log(result)
  product.productSkuList = []
  result.forEach(function(item) {
    product.productSkuList.push({
      skuSpec: item,
      price: 0,
    })
  })
}
// 展示添加页面
const showAdd = () => {
  isAudit.value = false
  action.value = '添加'
  dialogVisible.value = true
  Object.assign(product, defaultForm)
  detailImageList.value = []
  detailUrlList.value = []
  sliderUrlList.value = []
  sliderImageList.value = []
}
const categoryIdList = ref([])

// 添加或修改
const saveOrUpdate = () => {
  // product.sliderUrls = sliderImageList.value.join(',')
  product.sliderUrls = sliderUrlList.value.join(',')
  // product.detailsImageUrls = detailImageList.value.join(',')
  product.detailsImageUrls = detailUrlList.value.join(',')
  // 处理三级分类的id
  if (categoryIdList.value.length == 1) {
    product.category1Id = categoryIdList.value[0]
  }

  if (categoryIdList.value.length == 2) {
    product.category1Id = categoryIdList.value[0]
    product.category2Id = categoryIdList.value[1]
  }

  if (categoryIdList.value.length == 3) {
    product.category1Id = categoryIdList.value[0]
    product.category2Id = categoryIdList.value[1]
    product.category3Id = categoryIdList.value[2]
  }
  if (!product.id) {
    saveData()
  } else {
    updateData()
  }
}
const saveData = async () => {
  await SaveProduct(product)
  dialogVisible.value = false
  ElMessage.success('操作成功')
  fetchPage()
}

const updateData = async () => {
  await updateProduct(product)
  dialogVisible.value = false
  ElMessage.success('操作成功')
  fetchPage()
}

const showEdit = row => {
  isAudit.value = false
  detailImageList.value = []
  detailUrlList.value = []
  sliderUrlList.value = []
  sliderImageList.value = []
  action.value = '编辑'
  getById(row.id)
  props.checkStrictly = false
  dialogVisible.value = true
}

const getById = async id => {
  const { data } = await getProductById(id)
  Object.assign(product, data)

  //分类赋值
  categoryIdList.value = [
    product.category1Id,
    product.category2Id,
    product.category3Id,
  ]

  //处理图片
  sliderUrlList.value = product.sliderUrls.split(',')
  sliderUrlList.value.forEach(url => {
    sliderImageList.value.push({ url: url })
  })
  // console.log(sliderUrlList.value)
  // console.log(sliderImageList.value)
  // sliderUrlList.value = sliderImageList.value

  // 处理规格数据
  specValueList.value = JSON.parse(product.specValue)

  // 处理sku
  product.productSkuList.forEach(sku => {
    sku.skuSpec = sku.skuSpec.split(',').join(' * ')
    sku.skuSpecList = sku.skuSpec.split(',')
  })

  // 处理详情图片
  detailUrlList.value = product.detailsImageUrls.split(',')
  detailUrlList.value.forEach(url => {
    //KEYPOINT 在这里卡了好久啊，单词拼错了。。。
    detailImageList.value.push({ url: url })
  })

  //加载分类品牌
  getBrandList()
  getUnitList()
  getSpecList()
}
// 删除
const handleDelete = async id => {
  ElMessageBox.confirm('此操作将永久删除该记录, 是否继续?', 'Warning', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const res = await deleteProductById(id)
      if (res.code === 200) {
        ElMessage.success('删除成功')
        fetchPage()
      }
    })
    .catch(() => {
      ElMessage.info('取消删除')
    })
}

// 下架
const takeoff = async id => {
  const res = await takeoffProduct(id)
  if (res.code === 200) {
    ElMessage.success('成功')
    fetchPage()
  } else ElMessage.error(res.message)
}

// 上架
const takeon = async id => {
  const res = await takeonProduct(id)
  if (res.code === 200) {
    ElMessage.success('成功')
    fetchPage()
  } else ElMessage.error(res.message)
}
// 展示审核页面
const auditId = ref('')
const auditResult = ref('')
const showAudit = id => {
  isAudit.value = true
  dialogVisible.value = true
  getById(id)
  auditId.value = id
}
// 审核通过
const auditPass = () => {
  auditResult.value = 1
  doAudit()
}
// 审核不通过
const auditNotPass = () => {
  auditResult.value = -1
  doAudit()
}
// 审核
const doAudit = async () => {
  const res = await auditProduct(auditId.value, auditResult.value)
  if (res.code === 200) {
    ElMessage.success('成功')
    fetchPage()
  } else ElMessage.error(res.message)
  dialogVisible.value = false
}

onMounted(() => {
  fetchPage()
  getBrandList()
  getUnitList()
  getSpecList()
})
</script>

<style scoped></style>
